package com.obrempon.credit.market.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.CountDownTimer
import android.view.View
import android.widget.SeekBar
import androidx.recyclerview.widget.GridLayoutManager
import com.obrempon.credit.market.R
import com.obrempon.credit.market.common.CommonActivity
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.configs.ObremponConfigs
import com.obrempon.credit.market.databinding.ObremponApplyActBinding
import com.obrempon.credit.market.databinding.ObremponApplyDetailsChildItemBinding
import com.obrempon.credit.market.databinding.ObremponApplyDetailsItemBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.adapter.ObremponApplyDayApt
import com.obrempon.credit.market.ui.dialog.ObremponApplyGuideDialog
import com.obrempon.credit.market.utils.ObremponDensityUtil
import com.obrempon.credit.market.utils.decoration.GridSpacingItemDecoration
import com.obrempon.credit.market.utils.helper.ObremponConfigsHelper
import com.obrempon.credit.market.utils.helper.ObremponProcessHelper
import com.obrempon.credit.market.utils.helper.TestAnalysisAddEvent
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedKey
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal


/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/9/25 19:21
 * @Annotation：申请贷款
 */
class ObremponApplyAct: CommonActivity() {
    lateinit var binding: ObremponApplyActBinding
    private var countdownTimer: MyCountDownTimer? = null
    //等待时长
    private var countdown = 10 * 60

    //老客申请金额刻度
    private var mScale = 0
    private var minAmount = 0//最小值

    private var dayAdapter: ObremponApplyDayApt? = null
    //埋点备注
    var eventRemark = ""

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, ObremponApplyAct::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun takeObremponRootView(): View {
        binding = ObremponApplyActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        setObremponRootParentBackgroundColor(getColor(R.color.color_ff0569ff))
        setObremponTitleBarVisibility(View.VISIBLE)
        setObremponTextTitle(getString(R.string.obrempon_apply_title))
        setObremponTextTitleColor(getColor(R.color.white))
        setObremponBackBtnRes(R.mipmap.obrempon_back_white_icon)
        setObremponRightBtnRes(R.mipmap.obrempon_customer_icon)

        initObremponApplyLoanRefreshLayout()
        initObremponApplyDaysView()
        binding.applyContentLayout.visibility = View.GONE
        binding.btnApplySubmit.isEnabled = false
    }

    override fun initObremponListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark,takeObremponApplyProductName(),takeObremponApplyProductToken())
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,eventRemark)
        }
        binding.applyAmountSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                // 当进度改变时调用
                val showProcess = progress * mScale + minAmount
                binding.textAmount.text = "$showProcess"
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                // 当用户开始触摸SeekBar（按下）时调用
            }
            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                // 当用户结束触摸SeekBar（抬手）时调用
                loadObremponApplyDetailsAction()
            }
        })

        //提交
        binding.btnApplySubmit.setOnClickListener {
            showObremponLoading()
            submitObremponApplyAction()
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_LOAN_APPLY_SUBMIT,eventRemark)
        }
    }

    override fun takeObremponData() {
        showObremponLoading()
        loadObremponApplyDetailsAction()

        //上报 Battery 和 Wifi 信息
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SYC_BATTERY_WIFI))
    }

    /* 初始化刷新 */
    private fun initObremponApplyLoanRefreshLayout() {
        binding.applyRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.applyRefreshLayout.setOnRefreshListener {
            loadObremponApplyDetailsAction()
        }
    }

    /**
     * 选择days列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initObremponApplyDaysView(){
        binding.applyDaysView.setHasFixedSize(true)
        binding.applyDaysView.isNestedScrollingEnabled = false
        binding.applyDaysView.isFocusableInTouchMode = false //不需要焦点
        val decoration = ObremponDensityUtil.dp2px(9f)
        binding.applyDaysView.addItemDecoration(GridSpacingItemDecoration(3,decoration,false))
        val layoutManager = GridLayoutManager(getContext(),3)
        binding.applyDaysView.layoutManager = layoutManager
        dayAdapter = ObremponApplyDayApt(binding.applyDaysView)
        dayAdapter?.setOnItemChildClickListener { _, _, position ->
            val item = this.dayAdapter!!.getItem(position)
            if (!item.optBoolean("isEnabled",true) || item.optBoolean("isSelect",false)){
                return@setOnItemChildClickListener
            }
            for (i in 0..<dayAdapter!!.itemCount){
                val model = dayAdapter!!.getItem(i)
                model.put("isSelect",false)
                if (i == position){
                    model.put("isSelect",true)
                }
            }
            dayAdapter?.notifyDataSetChanged()

            //刷新数据
            loadObremponApplyDetailsAction()
        }
        binding.applyDaysView.adapter = dayAdapter
    }

    /**
     * 获取查看的产品名称
     */
    private fun takeObremponApplyProductName(): String {
        return intent.extras!!.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    private fun takeObremponApplyProductToken(): String {
        return intent.extras!!.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 获取贷款金额
     */
    private fun takeObremponApplyAmount(): String {
        return binding.textAmount.text.toString()
    }

    /**
     * 获取贷款期限
     */
    private fun takeObremponApplyDuration(): String {
        var days = ""
        if (dayAdapter!!.itemCount > 0){
            for (i in 0..<dayAdapter!!.itemCount){
                val item = dayAdapter!!.getItem(i)
                if (item.optBoolean("isSelect",false)){
                    days = item.optString("day")
                    break
                }
            }
        }
        return days
    }

    /**
     * 不可选择贷款额度
     */
    fun showObremponApplyNotOptionalViews(data: JSONObject) {
        binding.applyAmountSeekBar.visibility = View.GONE
        binding.textMinAmount.visibility = View.GONE
        binding.textMaxAmount.visibility = View.GONE
    }

    /**
     * 允许选择贷款额度
     */
    fun showObremponApplyOptionalViews(data: JSONObject) {
        //最小可选额度
        minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString().toInt()
        //最大值为剩余额度
        var maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString().toInt()
        //显示额度
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString().toInt()
        //颗粒度
        mScale = data.optInt("granularity")
        if (maxAmount <= minAmount){
            maxAmount = minAmount
        }

        //设置最大值
        val maxProcess = (maxAmount - this.minAmount) / mScale
        binding.applyAmountSeekBar.max = maxProcess
        //设置当前值
        val showAmount = (amount - this.minAmount) / mScale
        binding.applyAmountSeekBar.progress = showAmount

        binding.applyAmountSeekBar.visibility = View.VISIBLE
        binding.textMinAmount.visibility = View.VISIBLE
        binding.textMinAmount.text = String.format(getString(R.string.obrempon_apply_choose_amount_min),minAmount)
        binding.textMaxAmount.visibility = View.VISIBLE
        binding.textMaxAmount.text = String.format(getString(R.string.obrempon_apply_choose_amount_max),maxAmount)

        //显示引导dialog
        showObremponApplyGuideDialog(data)
    }

    /**
     * 设置贷款明细
     */
    fun showObremponApplyDetailsList(data: JSONObject) {
        binding.applyContentLayout.visibility = View.VISIBLE
        binding.btnApplySubmit.isEnabled = true
        startObremponApplyCountdownTimer()

        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        binding.textAmount.text = amount

        //明细
        val array = data.optJSONArray("detailItemList")
        val detailItemList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                val item = array.optJSONObject(i)
                if (item.has("title") && item.optString("title") == "YES"){
                    detailItemList.add(item)
                }
            }
            for (i in 0..<detailItemList.size){
                val obj = detailItemList[i]
                val childArray = JSONArray()
                var isAddChild = false
                for (n in 0..<array.length()){
                    val item = array.optJSONObject(n)
                    if (obj.optString("showName") == item.optString("showName")){
                        isAddChild = true
                        childArray.put(item)
                        continue
                    }
                    if (item.has("title") && item.optString("title") == "YES"){
                        isAddChild = false
                        continue
                    }
                    if (isAddChild){
                        childArray.put(item)
                    }
                }
                obj.put("childList",childArray)
            }
        }

        val boldTypeface = Typeface.createFromAsset(assets,"fonts/Roboto-Bold.ttf")
        binding.applyDetailsLayout.removeAllViews()
        detailItemList.forEach {
            val itemBinding = ObremponApplyDetailsItemBinding.inflate(layoutInflater)
            val childList = it.optJSONArray("childList")
            if (childList != null){
                for (i in 0..<childList.length()){
                    val childItem = childList.optJSONObject(i)
                    val childView = ObremponApplyDetailsChildItemBinding.inflate(layoutInflater)
                    childView.textDetailsTitle.text = childItem.optString("showName")
                    childView.textDetailsTitle.setTextColor(getColor(R.color.color_ff999999))
                    childView.textDetailsValue.text = childItem.optString("showDetail")
                    childView.textDetailsValue.setTextColor(getColor(R.color.black))

                    if (childItem.has("title") && childItem.optString("title") == "YES"){
                        childView.textDetailsTitle.typeface = boldTypeface
                        childView.textDetailsTitle.setTextColor(getColor(R.color.color_ff0569ff))
                        childView.textDetailsValue.typeface = boldTypeface
                        childView.textDetailsValue.setTextColor(getColor(R.color.color_ff0569ff))
                    }
                    childView.textOldValue.visibility = View.GONE
                    if (childItem.has("oldDetail")){
                        childView.textOldValue.visibility = View.VISIBLE
                        childView.textOldValue.text = childItem.optString("oldDetail")
                        childView.textDetailsValue.setTextColor(getColor(R.color.color_ffff3e30))
                    }
                    childView.discountLayout.visibility = View.GONE
                    if (childItem.has("discount")){
                        childView.discountLayout.visibility = View.VISIBLE
                        childView.textDiscount.text = childItem.optString("discount")
                    }
                    itemBinding.detailsItemLayout.addView(childView.root)
                }
            }
            binding.applyDetailsLayout.addView(itemBinding.root)
        }
    }

    /**
     * 设置贷款时长列表
     */
    private fun showObremponApplyDaysList(data: JSONObject){
        if (dayAdapter!!.itemCount == 0){
            //默认天数
            val defaultDays = data.optString("days")
            val daysArray = data.optJSONArray("daysArray")
            val dayList = arrayListOf<JSONObject>()
            if (daysArray != null) {
                //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                var isNeedAdd = true
                for (i in 0..<daysArray.length()){
                    if (daysArray.optString(i) == defaultDays){
                        isNeedAdd = false
                        break
                    }
                }
                if (isNeedAdd){
                    daysArray.put(0,defaultDays)
                }

                for (i in 0..<daysArray.length()){
                    val day = daysArray.optString(i)
                    val obj = JSONObject()
                    obj.put("day",day)
                    obj.put("isSelect",day == defaultDays)
                    obj.put("isEnabled",true)
                    dayList.add(obj)
                }
            } else {
                val obj = JSONObject()
                obj.put("day",defaultDays)
                obj.put("isSelect",true)
                obj.put("isEnabled",true)
                dayList.add(obj)
            }
            dayAdapter?.data = dayList
        }
    }

    /**
     * 贷款申请成功
     */
    fun showObremponApplySuccess() {
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        //刷新产品列表
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PRODUCT_REFRESH))
        hideObremponLoading()

        //是否包含SMS权限
        val permissionList = ObremponConfigsHelper.takeObremponPermissionsList()
        if (permissionList.contains(Manifest.permission.READ_SMS)){
            //进入SMS权限使用说明页面
            onIntent(ObremponWaitMSGAct::class.java)
        } else {
            //刷新主流程
            publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESH))
            //上报所有设备数据
            publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SYC_ALL_DEVICE))
        }
        finish()
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    fun showObremponLoanApplyFailed() {
        hideObremponLoading()
        finish()
    }

    /**
     * 展示引导dialog
     */
    private fun showObremponApplyGuideDialog(data: JSONObject){
        val isShowGuide = ObremponSharedHelper.queryObremponSharedBoolean(ObremponSharedKey.OBREMPON_DIALOG_GUIDE_APPLY_SHOW)
        if (isShowGuide){//已显示过
            return
        }
        //此处展示引导dialog
        ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_DIALOG_GUIDE_APPLY_SHOW,true)
        val loanApplyGuideDialog = ObremponApplyGuideDialog(this)
        loanApplyGuideDialog.setCancelable(true)
        loanApplyGuideDialog.setCanceledOnTouchOutside(false)
        loanApplyGuideDialog.show()
        loanApplyGuideDialog.showObremponApplyGuideData(data)
    }

    override fun hideObremponLoading() {
        super.hideObremponLoading()
        binding.applyRefreshLayout.isRefreshing = false
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        when(event.eventType){
            ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESHED -> {
                //需要校验 WhatsApp 或 SMS
                if (ObremponProcessHelper.isObremponAuthCheckWhatsApp() || ObremponProcessHelper.isObremponAuthCheckSMS()){
                    ObremponCheckMobileAct.start(this)
                }
                finish()
            }
            else -> {

            }
        }
    }

    /**
     * 开启倒计时
     */
    private fun startObremponApplyCountdownTimer(){
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        countdown = 10 * 60
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    /**
     * 显示状态
     */
    private fun showObremponApplyCountdownText(){
        val seconds = countdown % 60
        val minutes = countdown / 60 % 60
        binding.textApplyCountdown.text = String.format("%s:%s", if (minutes < 10) "0$minutes" else "$minutes", if (seconds < 10) "0$seconds" else "$seconds")
    }

    private fun showObremponApplyCountdownComplete(){
        loadObremponApplyDetailsAction()
    }

    class MyCountDownTimer(private val act: ObremponApplyAct, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showObremponApplyCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showObremponApplyCountdownComplete()
        }
    }

    /**
     * 获取贷款信息
     */
    private fun loadObremponApplyDetailsAction(){
        val params = JSONObject().addCommonParams()
        params.put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_APPLY_CUSTOM_LIMIT_PATH)
        params.put("product",takeObremponApplyProductName())
        params.put("token",takeObremponApplyProductToken())
        params.put("amount",takeObremponApplyAmount())
        params.put("oldFlag","YES")
        if (ObremponConfigs.isObremponSwahili()){
            params.put("localLanguage","YES")
        }
        val applyDays = takeObremponApplyDuration()
        if (applyDays.isNotEmpty()){
            params.put("days",applyDays)
        }
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //是否允许修改申请金额，不允许修改则不显示Seekbar
                    val chooseAmountFlag = obj.optBoolean("chooseAmountFlag",false)
                    when(chooseAmountFlag){
                        true -> {//允许选择贷款额度
                            showObremponApplyOptionalViews(obj)
                        }
                        else -> {//不允许选择贷款额度
                            showObremponApplyNotOptionalViews(obj)
                        }
                    }
                    showObremponApplyDaysList(obj)
                    showObremponApplyDetailsList(obj)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 创建贷款申请订单
     */
    private fun submitObremponApplyAction(){
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_LOAN_APPLY_ORDER_CREATE_PATH)
            put("product",takeObremponApplyProductName())
            put("token",takeObremponApplyProductToken())
            put("amount",takeObremponApplyAmount())
            put("days",takeObremponApplyDuration())
        }
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                showObremponApplySuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${takeObremponApplyProductName()} LoanApply Page"
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_LOAN_APPLY_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_LOAN_APPLY_END,eventRemark)
    }
}